@pushonce('scripts')
    <script>
        // 通用的表格行添加事件处理
        function handleAppendRow(event) {
            console.log('append-row event received:', event);
            const tbody = document.getElementById('table-body');
            console.log('tbody:', tbody);

            if (tbody) {
                const temp = document.createElement('tbody');
                temp.innerHTML = event.detail[0].html.trim();
                tbody.insertBefore(temp.firstChild, tbody.firstChild);
                console.log('tbody after insert:', tbody);
                htmx.process(tbody);
            } else {
                console.error('table-body element not found');
            }
        }

        // 通用的表格行更新事件处理
        function handleUpdateRow(event) {
            console.log('update-row event received:', event.detail[0]);
            const id = event.detail[0].id;
            const old = document.querySelector('tr[data-id="' + id + '"]');

            if (old) {
                const newTr = document.createElement('tr');
                newTr.setAttribute('data-id', old.getAttribute('data-id'));
                newTr.innerHTML = event.detail[0].html.trim();
                old.replaceWith(newTr);
                const tbody = document.getElementById('table-body');
                htmx.process(tbody);
            } else {
                console.error('Row with id ' + id + ' not found');
            }
        }

        // 通用的创建事件处理（支持不同的事件名称）
        function handleCreateEvent(event, eventName) {
            console.log(eventName + ' event received:', event.detail);
            const tbody = document.getElementById('table-body');

            if (tbody) {
                const temp = document.createElement('tbody');
                temp.innerHTML = event.detail.html.trim();
                tbody.insertBefore(temp.firstChild, tbody.firstChild);
                htmx.process(tbody);
            } else {
                console.error('table-body element not found for ' + eventName);
            }
        }

        // 注册事件监听器
        window.addEventListener('append-row', handleAppendRow);
        window.addEventListener('update-row', handleUpdateRow);

        // 注册各种创建事件
        window.addEventListener('role-created', (event) => handleCreateEvent(event, 'role-created'));
        window.addEventListener('permission-created', (event) => handleCreateEvent(event, 'permission-created'));
        window.addEventListener('user-created', (event) => handleCreateEvent(event, 'user-created'));

        // HTMX CSRF Token 配置
        document.body.addEventListener('htmx:configRequest', (evt) => {
            evt.detail.headers['X-CSRF-Token'] = document.querySelector('meta[name="csrf-token"]').content;
        });

        // 调试信息
        console.log('Table scripts loaded successfully');
    </script>
@endpushonce

@pushonce('head')
    <meta name="csrf-token" content="{{ csrf_token() }}">
@endpushonce
